package com.bitejiuyeke.forum.controller;

import com.bitejiuyeke.forum.common.AppResult;
import com.bitejiuyeke.forum.common.ResultCode;
import com.bitejiuyeke.forum.config.AppConfig;
import com.bitejiuyeke.forum.model.Article;
import com.bitejiuyeke.forum.model.Board;
import com.bitejiuyeke.forum.model.User;
import com.bitejiuyeke.forum.services.IArticleService;
import com.bitejiuyeke.forum.services.IBoradService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 666
 * Date: 2023-12-25
 * Time: 17:48
 */

@Api(tags = "文章接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Resource
    private IArticleService articleService;
    @Resource
    private IBoradService boradService;
    /**
     *  发布新帖
     * @param boardId
     * @param title
     * @param content
     * @return
     */
    @ApiOperation("发布新帖")
    @PostMapping("/create")
    public AppResult create (HttpServletRequest request, @ApiParam("板块Id") @RequestParam("boardId") @NonNull Long boardId,
                             @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                             @ApiParam("文章内容") @RequestParam("content") @NonNull String content){
        // 校验用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 校验板块
        Board board = boradService.selectById(boardId.longValue());
        if(board == null || board.getDeleteState() == 1 || board.getState() == 1){
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            return  AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }
        //封装文章对象
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setBoardId(boardId);
        article.setUserId(user.getId());
        //调用service
        articleService.create(article);
        //响应
        return AppResult.success();
    }
    @ApiOperation("获取板块的文章")
    @GetMapping("/getAllBoardId")
    public AppResult<List<Article>>  getAllBoardId(@ApiParam("板块id") @RequestParam(value = "boardId",required = false) Long boardId){
        List<Article> articles;
      if(boardId == null){
          articles = articleService.selectAll();

      } else {
          articles = articleService.selectAllByBoardId(boardId);
      }
        if(articles == null){
            articles = new ArrayList<>();
        }
        //响应结果
        return AppResult.success(articles);
    }
    @ApiOperation("根据帖子id获取帖子详情")
    @GetMapping("/details")
    public  AppResult<Article>  getDetails(HttpServletRequest request,@ApiParam("帖子id") @RequestParam("id")@NonNull Long id){
           //获取登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //调用service
        Article article = articleService.selectDetailById(id);
        //判断结果
        if(article == null){
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        //判断当前用户是否为作者
        if(user.getId().equals(article.getUserId())){
        article.setOwn(true);
        }
        //响应结果
        return AppResult.success(article);
    }
    @ApiOperation("修改帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("帖子id") @RequestParam("id") @NonNull Long id,
                            @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                            @ApiParam("帖子内容") @RequestParam("content") @NonNull String content){
        //获取登录用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
       //校验用户状态
        if(user.getState() == 1){
            //返回错误描述
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 查询帖子详情
        Article article = articleService.selectById(id);
        //校验帖子是否有效
        if(article == null){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //判断用户是否是作者
   if(user.getId()!=article.getUserId()){
       return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
   }
        if(article.getDeleteState() == 1){
            return AppResult.failed(ResultCode.FAILED);
        }
       //调用service
       articleService.modify(id,title,content);
       //更新帖子，打印日志
       log.info("用户{}修改了帖子{}",user.getId(),id);
       //返回结果
        return AppResult.success();
    }
    @ApiOperation("点赞")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(
            HttpServletRequest request,@ApiParam("帖子id") @RequestParam("id") @NonNull Long id){
     //校验用户状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //判断用户是否被禁言
        if(user.getState() == 1){
            //用户已禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
      //调用service
        articleService.thumbsUpById(id);
        //返回结果

        return AppResult.success();
    }
    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
            @ApiParam("帖子id") @RequestParam("id") @NonNull Long id){
         //校验用户状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1){
          //  用户已禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //查询帖子详情
        Article article = articleService.selectById(id);
        //校验帖子状态
        if(article == null || article.getDeleteState()==1){
            //帖子不存在
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //校验登录用户是不是作者
        if(user.getId() != article.getUserId()){
            return  AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        //调用service
        articleService.deleteById(id);
        //返回结果
        return AppResult.success();
    }

    @ApiOperation("获取用户帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                                @ApiParam("用户id") @RequestParam(value = "userId",required = false) Long userId){
    //如果userid为空，则获取当前登录用户的id
        if(userId == null){
            //获取session
            HttpSession session = request.getSession(false);
            //获取当前登录用户
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        //调用service
        List<Article> articleList = articleService.selectByUserId(userId);
        return AppResult.success(articleList);
    }


}
